package org.example.project.common.validator;

import org.springframework.util.Assert;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidationException;
import java.util.Iterator;
import java.util.Set;

/**
 * 实体验证器
 *
 * @author wenxy
 * @date 2020/10/12
 */
public final class Validator {

    private static javax.validation.Validator VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();

    protected Validator() {
        throw new UnsupportedOperationException();
    }

    /**
     * 验证dto（好像不太需要，kafka有异常拦截器，通过java-validator验证失败直接统一处理就可以了）
     *
     * @param pojo   pojo
     * @param groups 验证组
     * @return isValid
     */
    public static <T> void valid(T pojo, Class<?>... groups) {
        Assert.state(VALIDATOR != null, "No Validator set");
        Set<ConstraintViolation<T>> violations = VALIDATOR.validate(pojo, groups);

        if (violations.isEmpty()) {
            return;
        }

        StringBuilder sb = new StringBuilder("pojo is invalid: ");
        for (Iterator<ConstraintViolation<T>> it = violations.iterator(); it.hasNext(); ) {
            ConstraintViolation<T> violation = it.next();
            sb.append(violation.getPropertyPath()).append(" - ").append(violation.getMessage());
            if (it.hasNext()) {
                sb.append("; ");
            }
        }
        throw new ValidationException(sb.toString());
    }
}
